import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/order_item_info.dart';
import 'package:app/src/http/bean/wroks/product_bean.dart';
import 'package:app/src/http/bean/wroks/special_clauses.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/a_combined_utils.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../../http/bean/clockin/attendances.dart';
import '../../../../../http/bean/wroks/carfreightrates_bean.dart';
import '../../../../../http/bean/wroks/workreview_bean.dart';
import '../../../../../http/model/config_model.dart';
import '../../../../app_ui.dart';

///加班审核，排班
class UiWorkReviewScheduling {
  static bool isScheduling = false; //是否排班
  static List<Scheduling>? datas = null;

  ///初始化，记得手动调用一次。
  static init(List<Scheduling>? Schedulings) {
    isScheduling = false;
    datas = Schedulings;
    if (datas == null) {
      datas = [];
    }
    var data = Scheduling();
    data.factory = AppDataConfig.getFactory(); //工厂

    //模拟班组班次信息
    // MyGroupBcInfo? GroupBcInfo = MyGroupBcInfo();
    // GroupBcInfo.GroupId = "0";
    // GroupBcInfo.GroupName = "测试班组";
    // List<MyAttendances> Attendances = [];
    // for (int i = 0; i <= 3; i++) {
    //   MyAttendances? Attendance = MyAttendances();
    //   Attendance.AttendanceId = i.toString();
    //   Attendance.WorkTypeName = "班次" + i.toString();
    //   Attendance.OnWorkTime = "08:00";
    //   Attendance.OffWorkTime = "16:40";
    //   Attendances.add(Attendance);
    // }
    // GroupBcInfo.Attendances = Attendances;
    // data.GroupBcInfo = GroupBcInfo;
    //模拟班组信息结束

    datas?.add(data);
  }

  static Widget build(BuildContext context, {String? title}) {
    return StatefulBuilder(builder: (context, setState) {
      List<Widget> children = [];
      if (StringUtils.isEmpty(title)) {
        title = AppStrings.of(context).Scheduling; //排班
      }
      children.add(UiBase.title(context, title,
          bottom: AppEdgeInsets.margin_bottom)); //标题
      children.add(UiBase.itemWithCheckBox(
          context, AppStrings.of(context).Scheduling, isScheduling, (value) {
        if (value != null) {
          setState(() {
            isScheduling = value;
          });
        }
      }, true)); //排班
      if (isScheduling) {
        children.add(_table(context, datas!));
      }
      var column = UiBase.column(context, children);
      var card = UiCard.build(context, column);
      return card;
    });
  }

  ///fixme Table表格里的行TabRow;每一行的表格数量必须相等。不然报错。
  ///fixme table嵌套table实现单元格合并。

  //表格线条颜色
  static Color _BorderColor = Colors.black12;

  //表格线条宽度
  static double _width = 1;

  ///背景色表格标题
  static Color _backgroundColorWithTableTitle = Colors.black12;
  static Color _backgroundColorWithWhite = Colors.white;
  static Color _backgroundColorWithGrey = ColorUtils.parseColor("#F7F6F3");
  static StateSetter? _setState = null;

  static Widget _table(BuildContext context, List<Scheduling> datas) {
    if (datas.length <= 0) {
      return LibUi.getEmptyView();
    }
    //fixme 表格
    return StatefulBuilder(builder: (context, setState) {
      _setState = setState;
      //可以水平滑动的表格
      var scrolltable = _scrolltable(context, datas);
      //水平滑动效果
      var singleChildScrollView = SingleChildScrollView(
          child: scrolltable, scrollDirection: Axis.horizontal);
      return Center(
        child: Container(
          child: singleChildScrollView,
          //width: 400,
        ),
      );
    });
  }

  ///水平滑动表格
  static Widget _scrolltable(BuildContext context, List<Scheduling> datas) {
    var children = <TableRow>[];
    //第一行标题栏
    var tableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: [
          _text(AppStrings.of(context).Date), //日期
          _text(AppStrings.of(context).FactoryName3), //工厂
          _text(AppStrings.of(context).ClassName), //班组
          _text(AppStrings.of(context).shift), //班次
          _text(AppStrings.of(context).Operation), //操作
        ]);
    children.add(tableRow);
    //第二行，内容行。
    for (int i = 0; i < datas.length; i++) {
      var data = datas[i];
      List<Widget> rowChildren = [];
      //日期
      var dataTime = _text(
          "${DateTimeUtils.getDateTimeFormat(dateTime: data.dateTime, showSecond: false, dateAndTime: false)}");
      rowChildren.add(Row(
        children: [
          InkWell(
            child: Icon(
              Icons.add,
              color: Colors.blueAccent,
            ),
            onTap: () {
              _setState?.call(() {
                var add = data.add();
                datas.add(add);
                datas.sort((left, right) {
                  return left.dateTime
                      .difference(right.dateTime)
                      .inSeconds; //按照字段dateTime时间，从小到大排列。
                });
              });
            },
          ),
          dataTime
        ],
      ));
      //工厂
      var factory =
          _materialButton("${data.factory?.FactoryName ?? ""}", onPressed: () {
            //print("点击事件");
        ConfigModel.getFactorygetlist(context, false, (value) {
          //print("返回结果：${value?.Data}");
          if (value != null && value!.isSuccessForData()) {
            AppDialog.showDialogWithRollerPicker(context,
                    datas: value.Data, data: data.factory)
                ?.then((value) {
                  //print("工厂：${value?.FactoryName}\t${value?.FactoryId}\t${data.factory?.FactoryName}");
              if (value != null) {
                _setState?.call(() {
                  if (data.factory?.FactoryId != value?.FactoryId) {
                    //工厂发生改变;班组和班次重置
                    data.GroupBcInfo = null;
                    data.Attendance = null;
                  }
                  data.factory = value;
                });
              }
            });
          }
        });
      });
      rowChildren.add(factory);
      //班组
      String? GroupName = data.GroupBcInfo?.GroupName;
      if (StringUtils.isEmpty(GroupName)) {
        GroupName = AppStrings.of(context).ClickSelect;
      }
      var classTeam = _materialButton("$GroupName", onPressed: () {
        ConfigModel.getSchedulingsWithGroupBcInfo(
            context, true, data.factory?.FactoryId, (value) {
          if (value != null && value!.isSuccessForData()) {
            AppDialog.showDialogWithRollerPicker<MyGroupBcInfo>(context,
                    datas: value.Data, data: data.GroupBcInfo)
                ?.then((value) {
              if (value != null) {
                _setState?.call(() {
                  if (data.GroupBcInfo?.GroupId != value?.GroupId) {
                    //班组改变;班次重置
                    data.Attendance = null;
                  }
                  data.GroupBcInfo = value;
                });
              }
            });
          }else{
            showDialogWithInfo(context,content: value?.MsgDetail??"");
          }
        });
      });
      rowChildren.add(classTeam);
      //班次
      var _key = data.Attendance?.getAttendanceKey();
      List<Widget> shiftChildren = [];
      data.GroupBcInfo?.Attendances?.forEach((element) {
        var isCheck = element.getAttendanceKey() == _key; //判断当前班次是否选中。
        var _text =
            "${element?.WorkTypeName}: ${element.OnWorkTime} - ${element.OffWorkTime}";
        Color color = Colors.grey;
        if (isCheck) {
          color = Colors.blueAccent;
        }
        var shift = _materialButton(_text, color: color, onPressed: () {
          _setState?.call(() {
            data.Attendance = element;
          });
        });
        shiftChildren.add(shift);
      });
      rowChildren.add(Row(
        children: shiftChildren,
      ));
      //向下同步
      var btn = _materialButton(AppStrings.of(context).Synchronousdown,
          onPressed: () {
        _setState?.call(() {
          for (int j = i; j < datas.length; j++) {
            data.copy(datas[j]);
          }
        });
      });
      rowChildren.add(btn);
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.all(
          color: _BorderColor, width: _width, style: BorderStyle.solid),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: IntrinsicColumnWidth(),
        1: IntrinsicColumnWidth(),
        2: IntrinsicColumnWidth(),
        3: IntrinsicColumnWidth(),
        4: IntrinsicColumnWidth(),
      },
      children: children,
    );
    return table;
  }

  //fixme 条目颜色背景
  static Color _getColor(int i) {
    Color _color = _backgroundColorWithWhite;
    //print("=============$i ${i%2}");
    if (i % 2 == 0) {
      _color = _backgroundColorWithGrey;
    }
    return _color;
  }

  //文本
  static Widget _text(String? text) {
    // return Center(
    //   child: Text(text ?? ""),
    // );
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: 36.0, //最小高度
        ),
        child: Center(
          child: Text(text ?? ""),
        ),
      ),
    );
  }

  //复选框
  //isChecked 是否选中
  //isEnable 是否可操作
  //onChanged 选中回调
  static Widget _checkbox(bool isChecked,
      {bool isEnable = true, Function(bool)? onChanged}) {
    Color activeColor = Colors.blueAccent;
    Color inactiveColor = Colors.black;
    if (!isEnable) {
      //不可用，颜色变暗。
      activeColor = Colors.black12;
      inactiveColor = Colors.black12;
    }
    return Container(
      alignment: Alignment.center,
      // height: 30,
      // width: 30,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      child: CircleCheckbox(
        isEnable: isEnable,
        value: isChecked,
        //value 是否选中
        width: 20,
        //width 宽度
        height: 20,
        //height 高度
        activeColor: activeColor,
        //activeColor 选中时背景颜色
        inactiveColor: inactiveColor,
        //inactiveColor 未选中时颜色
        style: CircleCheckboxStyle.tick_hollow,
        //circle_point 圆点样式
        //checked: , 自定义选中组件；fixme 优先级比以上属性设置要高。
        //unChecked: ,自定义未选中组件
        onChanged: (bool) {
          //选中状态改变时回调，如点击时。
          //选中状态改变时回调。
          //setState(() {});
          if (isEnable) {
            onChanged?.call(bool);
          }
        },
      ),
    );
  }

  ///按钮
  static Widget _materialButton(String text,
      {VoidCallback? onPressed,
      double radius = 5,
      double height = 35,
      double width = 50,
      Color color = Colors.blueAccent,
      Color textColor = Colors.white,
      double fontSize = 14,
      EdgeInsetsGeometry margin = const EdgeInsets.only(left: 8, right: 8),
      EdgeInsetsGeometry padding =
          const EdgeInsets.only(left: 16, right: 16)}) {
    return Container(
      margin: margin,
      child: MaterialButton(
        padding: padding,
        height: height,
        minWidth: width,
        onPressed: () {
          onPressed?.call();
        },
        //label 右边控件（一般为文本），不能为空
        color: color,
        //color 按钮颜色
        splashColor: Colors.black12,
        //splashColor 点击时，飞溅扩散的颜色
        //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
        colorBrightness: Brightness.light,
        //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        //shape 形状
        textColor: Colors.white,
        //文本默认颜色
        child: Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: fontSize,
          ),
        ), //fixme 子控件
      ),
    );
  }
}
